import { useState, useCallback } from 'react';
import { Message, ThemeConfig, ConnectionStatus } from '../types';

interface AppState {
  messages: Message[];
  connectionStatus: ConnectionStatus;
  theme: ThemeConfig;
  isLoading: boolean;
}

export function useAppState() {
  const [state, setState] = useState<AppState>({
    messages: [],
    connectionStatus: { connected: false, retrying: false },
    theme: {
      userMessage: 'cyan',
      aiMessage: 'white',
      systemMessage: 'yellow',
      errorMessage: 'red',
      codeBlock: 'gray',
      inputArea: 'blue'
    },
    isLoading: false
  });

  const addMessage = useCallback((message: Omit<Message, 'id' | 'timestamp'>) => {
    const newMessage: Message = {
      ...message,
      id: Date.now().toString() + Math.random().toString(36).substr(2, 9),
      timestamp: new Date()
    };

    setState(prev => ({
      ...prev,
      messages: [...prev.messages, newMessage]
    }));

    return newMessage.id;
  }, []);

  const updateMessage = useCallback((id: string, updates: Partial<Message>) => {
    setState(prev => ({
      ...prev,
      messages: prev.messages.map(msg => 
        msg.id === id ? { ...msg, ...updates } : msg
      )
    }));
  }, []);

  const clearMessages = useCallback(() => {
    setState(prev => ({
      ...prev,
      messages: []
    }));
  }, []);

  const setConnectionStatus = useCallback((status: ConnectionStatus) => {
    setState(prev => ({
      ...prev,
      connectionStatus: status
    }));
  }, []);

  const setLoading = useCallback((loading: boolean) => {
    setState(prev => ({
      ...prev,
      isLoading: loading
    }));
  }, []);

  const updateTheme = useCallback((theme: Partial<ThemeConfig>) => {
    setState(prev => ({
      ...prev,
      theme: { ...prev.theme, ...theme }
    }));
  }, []);

  return {
    state,
    actions: {
      addMessage,
      updateMessage,
      clearMessages,
      setConnectionStatus,
      setLoading,
      updateTheme
    }
  };
}